import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:ichineseaplus/domain/core/constants/storage.constants.dart';
import 'package:ichineseaplus/infrastructure/dal/services/auth/auth.service.dart';
import 'package:ichineseaplus/infrastructure/dal/services/auth/dto/authenticate_user.body.dart';
import 'package:ichineseaplus/infrastructure/dal/services/user/dto/user.response.dart';
import 'package:ichineseaplus/infrastructure/dal/services/user/user.service.dart';

class AuthRepository {
  final AuthService _authService;
  final UserService _userService;
  final _storage = Get.find<GetStorage>();

  AuthRepository({
    required AuthService authService,
    required UserService userService,
  })  : _authService = authService,
        _userService = userService;

  Future<UserResponse> authenticateUser({
    required String loginName,
    required String password,
  }) async {
    try {
      final body =
          AuthenticateUserBody(loginName: loginName, password: password);
      final authenticateUserResponse =
          await _authService.authenticateUser(body);
      await _storage.write(
        StorageConstants.tokenAuthorization,
        authenticateUserResponse.result!.authToken,
      );

      final userResponse = await _userService.getUserProfile();

      await userResponse.save();

      return userResponse;
    } catch (err) {
      rethrow;
    }
  }

  Future<UserResponse> getUser() async {
    try {
      final response = await _userService.getUserProfile();
      response.save();
      return response;
    } catch (err) {
      rethrow;
    }
  }

  Future<bool> isAuthenticated() async {
    try {
      final hasToken = _storage.hasData(StorageConstants.tokenAuthorization);
      final hasUser = _storage.hasData(StorageConstants.user);
      return hasToken && hasUser;
    } catch (err) {
      rethrow;
    }
  }

  Future<void> logoutUser() async {
    try {
      await _storage.erase();
    } catch (err) {
      rethrow;
    }
  }
}
